<template>
  <view class="video-page">
    <tab-banner :list="categories" :current="activeIndex" @onTabClick="tabClick"></tab-banner>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view v-else-if="videoList.length === 0" class="empty-state">
      <text class="empty-icon">🎬</text>
      <text class="empty-text">暂无视频数据</text>
    </view>
    
    <!-- 视频列表 -->
    <view class="video-list" v-else>
      <view class="video-item" 
            v-for="item in videoList" 
            :key="item.id" 
            @click="goToDetail(item.id)"
      >
        <image class="video-cover" :src="item.cover"></image>
        <view class="video-duration">{{ item.duration }}</view>
        <view class="video-info">
          <view class="video-title">{{ item.title }}</view>
          <view class="video-meta">
            <text class="author">{{ item.author }}</text>
            <text class="play-count">{{ item.playCount }}次播放</text>
          </view>
        </view>
        <!-- 点赞按钮 -->
        <view class="like-btn" @click.stop="toggleLike(item.id)">
          <text class="like-icon" :class="{ liked: isVideoLiked(item.id) }">❤️</text>
          <text class="like-count">{{ item.likeCount || 0 }}</text>
        </view>
        <!-- 关注按钮 -->
        <button class="follow-btn" 
                @click.stop="toggleFollow(item.author)"
                :class="{ followed: isAuthorFollowed(item.author) }"
        >
          {{ isAuthorFollowed(item.author) ? '已关注' : '关注' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>
// 确保 tabBanner 组件路径正确（根据你的实际路径调整）
import tabBanner from "@/components/tabBanner.vue";

export default {
  components: { tabBanner },
  data() {
    return {
      categories: [],
      videoList: [],
      activeIndex: 0,
      loading: true,
      app: null
    };
  },
  onLoad() {
    this.app = getApp();
    this.loadVideoData();
  },
  onShow() {
    if (this.app.globalData.userInfo) {
      this.syncUserVideoState();
    }
  },
  methods: {
    async loadVideoData() {
      try {
        this.loading = true;
        
        if (this.app.globalData.videoData) {
          this.categories = this.app.globalData.videoData.categories || [];
          this.videoList = this.app.globalData.videoData.videoList || [];
          
          this.videoList = this.videoList.map(item => ({
            ...item,
            likeCount: item.likeCount || '0',
            isFollowed: this.isAuthorFollowed(item.author)
          }));
          console.log('视频首页加载数据成功，数量：', this.videoList.length);
        } else {
          this.categories = ["推荐", "千里眼", "搞笑", "娱乐", "社会", "音乐", "科技"];
          this.videoList = [];
        }
        
      } catch (e) {
        console.error('视频首页加载数据失败:', e);
        this.categories = ["推荐", "千里眼", "搞笑", "娱乐", "社会", "音乐", "科技"];
        this.videoList = [];
        uni.showToast({ title: '加载失败，使用默认分类', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },
    
    syncUserVideoState() {
      this.videoList = this.videoList.map(item => ({
        ...item,
        isFollowed: this.isAuthorFollowed(item.author)
      }));
    },
    
    isVideoLiked(videoId) {
      if (!this.app.globalData.userInfo) return false;
      return this.app.isContentLiked(videoId, 'video');
    },
    
    isAuthorFollowed(authorName) {
      if (!this.app.globalData.userInfo) return false;
      return this.app.isFollowed(authorName);
    },
    
    toggleLike(videoId) {
      if (!this.app.globalData.userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录后操作',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({ url: '/pages/tabBar/tabcompage/login/login' });
            }
          }
        });
        return;
      }
      
      const isLiked = this.isVideoLiked(videoId);
      this.app.toggleVideoLike(videoId, !isLiked);
      
      this.videoList = this.videoList.map(item => {
        if (item.id === videoId) {
          const num = Number(item.likeCount.replace(/[^\d]/g, ''));
          const newCount = !isLiked ? num + 1 : Math.max(0, num - 1);
          item.likeCount = newCount >= 10000 
            ? `${(newCount / 10000).toFixed(1)}万` 
            : `${newCount}`;
        }
        return item;
      });
      
      uni.showToast({
        title: !isLiked ? '点赞成功' : '取消点赞',
        icon: 'none'
      });
    },
    
    toggleFollow(authorName) {
      if (!this.app.globalData.userInfo) {
        uni.showModal({
          title: '提示',
          content: '请先登录后操作',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({ url: '/pages/tabBar/tabcompage/login/login' });
            }
          }
        });
        return;
      }
      
      const isFollowed = this.isAuthorFollowed(authorName);
      this.app.toggleVideoAuthorFollow(authorName, !isFollowed);
      
      this.videoList = this.videoList.map(item => {
        if (item.author === authorName) {
          item.isFollowed = !isFollowed;
        }
        return item;
      });
      
      uni.showToast({
        title: !isFollowed ? '关注成功' : '取消关注',
        icon: 'none'
      });
    },
    
    tabClick(index) {
      this.activeIndex = index;
      this.loadVideoData();
    },
    
    // 修正：跳转路径匹配你的实际详情页路径
    goToDetail(videoId) {
      console.log('触发视频跳转，ID：', videoId);
      const jumpUrl = `/pages/tabBar/video/video-detail/video-detail?id=${videoId}`;
      console.log('跳转路径：', jumpUrl);
      
      const videoItem = this.videoList.find(item => item.id === videoId);
      if (videoItem && this.app.globalData.userInfo) {
        this.app.recordView(videoId, videoItem, 'video');
      }
      
      uni.navigateTo({
        url: jumpUrl,
        fail: (err) => {
          console.error('视频详情页跳转失败：', err);
          uni.showToast({
            title: '页面跳转失败，请检查路径',
            icon: 'none',
            duration: 2000
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.video-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
}
.loading-text {
  font-size: 28rpx;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}
.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}
.empty-text {
  font-size: 28rpx;
}

.video-list {
  padding: 20rpx;
}
.video-item {
  background-color: #fff;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  position: relative;
}
.video-cover {
  width: 100%;
  height: 400rpx;
  object-fit: cover;
}
.video-duration {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  background-color: rgba(0,0,0,0.7);
  color: #fff;
  font-size: 22rpx;
  padding: 5rpx 10rpx;
  border-radius: 4rpx;
}
.video-info {
  padding: 20rpx;
}
.video-title {
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.video-meta {
  font-size: 24rpx;
  color: #999;
  display: flex;
  justify-content: space-between;
}

.like-btn {
  position: absolute;
  top: 20rpx;
  right: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5rpx;
  background-color: rgba(0,0,0,0.5);
  padding: 8rpx 12rpx;
  border-radius: 30rpx;
}
.like-icon {
  font-size: 28rpx;
  color: #fff;
  transition: all 0.3s ease;
}
.like-icon.liked {
  color: #ff4444;
  transform: scale(1.1);
  animation: pulse 0.5s ease;
}
.like-count {
  font-size: 20rpx;
  color: #fff;
}

.follow-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background-color: rgba(208,0,0,0.8);
  color: #fff;
  border-radius: 30rpx;
  padding: 5rpx 20rpx;
  font-size: 24rpx;
  transition: all 0.3s ease;
}
.follow-btn.followed {
  background-color: rgba(153,153,153,0.8);
}
.follow-btn:active {
  transform: scale(0.95);
  opacity: 0.8;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1.1); }
}
</style>